<template>
  <div>
    <van-nav-bar title="修改个人信息" left-arrow @click-left="goBack" />
    <van-form @submit="modify" v-if="personal">
      <van-field v-model="personal.phone" name="手机号码" label="手机号码" readonly />
      <van-cell-group inset>
        <van-field name="file" label="头像">
          <template #input>
            <van-uploader v-model="head" reupload max-count="1" :after-read="uploadFile" />
          </template>
        </van-field>
        <van-field v-model="personal.name" name="姓名" label="姓名" placeholder="姓名" maxlength="4" :rules="[{ required: true, message: '请填写姓名' }]" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { showDialog } from 'vant';
import { mapMutations } from 'vuex';
export default {
  data() {
    return {
      personal: null,
      head: [],
    }
  },
  activated() {
    this.personal = app.data;
    this.head = this.personal.head ? [{ url: this.personal.head }] : [];
  },
  methods: {
    ...mapMutations(['setPersonal']),
    goBack() {
      this.$router.back();
    },
    async uploadFile(file) {
      const params = new FormData();
      params.append("file", file.file);
      const data = await post('/upload', params);
      if (data.success) {
        this.head = [{ url: data.result.url }];
      }
    },
    async modify() {
      const params = {
        id: this.personal.id,
        name: this.personal.name,
        head: this.head[0]?.url,
      };
      const data = await post('/modify/member', params);
      if (!data.success) {
        return showDialog({ message: data.message });
      }
      showDialog({ message: '修改成功' });
      this.setPersonal(data.result);
      app.pop();
    }
  }
}
</script>


<style scoped lang="less">
.info {
  width: 100%;
  color: gray;
  margin-bottom: 40px;
  text-align: center;
  position: absolute;
  bottom: 20px;
}
</style>
